package com.dosh;

import android.app.Activity;
import android.database.Cursor;

	/**
	 * The Booking class describes an entry in the Booking table.
	 * A Booking is generated from the homepage and is the central part of the application. 
	 * The fields booking_ID and amount are necessary for are table entry.
	 */
public class Booking extends Activity{
	/**
	 * The ID of the Booking entry
	 */
	public long booking_ID;
	/**
	 * The Bookings amount
	 */
	public long amount;
	/**
	 * A short description of the Booking
	 */
	public String description;
	/**
	 * A List of all Items which are connected with this Booking
	 */
	public Item[] items;
	
	/**
	 * This Constructor is used, if there is no entry in the database.
	 * @param dba A reference to the DBAdapter
	 */
	public Booking(int amount, String description, Item[] items, DBAdapter dba) {
		
		this.amount = amount;
		this.description = description;
		this.items = items;
		
		dba.open();
		this.booking_ID = dba.insertBooking(amount, description);
		
		int i = 0;
		while(i < items.length) {
			dba.insertBooking_Item(items[i].item_ID, this.booking_ID);
			i++;
		}
		dba.close();
	}
	/**
	 * This Constructor is used, if there an entry already exists in the database.
	 * @param dba A reference to the DBAdapter
	 */
	public Booking(long booking_ID, DBAdapter dba) {
		
		this.booking_ID = booking_ID;
		dba.open();
		Cursor bCursor = dba.SELECTbyId("Booking", booking_ID);
		Cursor iCursor = dba.SELECTbyKey("Booking_Item", "Booking", booking_ID);
		dba.close();
		this.amount = bCursor.getInt(1);
		this.description = bCursor.getString(2);
		int i = 0;
		this.items = new Item[iCursor.getCount()];
		if(iCursor.getCount()!=0){
			do {
				this.items[i] = new Item(iCursor.getLong(1), dba);
				i++;
				if(!iCursor.isLast()){iCursor.moveToNext();}
			} while(!iCursor.isLast());
		}
	}
	/**
	 * This method updates the table entry
	 * @param dba A reference to the DBAdapter
	 * @return gives information,if the update was successful
	 */
	public boolean update(DBAdapter dba) 
	{
		boolean bool = true;
		dba.open();
		bool = dba.update("Booking", this.booking_ID, "Amount", this.amount);
		bool = dba.update("Booking", this.booking_ID, "Description", this.description);
		dba.delete("Booking_Item", "Booking", this.booking_ID);
		for(int i = 0;i < this.items.length; i++)
		{
			dba.insertBooking_Item(this.booking_ID, items[i].item_ID);
		}
		
		return bool;
	}

}
